from loguru import logger
import logging
import sys
import os


class LogConfig:
    def __init__(
        self,
        app,
        enable_console: bool = True,
        enable_file: bool = False,
        file_path: str = "logs/app.log",
        rotation: str = os.getenv("LOG_ROTATION", "100 MB"),
        retention: str = os.getenv("LOG_RETENTION", "30 days"),
        log_level: str = "INFO",
        format: str = "{time:YYYY-MM-DD HH:mm:ss}| <level>{level: <8}</level> | {module}:{line} | {message}",
    ):
        self.app = app
        self.enable_console = enable_console
        self.enable_file = enable_file
        self.file_path = file_path
        self.rotation = rotation
        self.retention = retention
        self.log_level = log_level
        self.format = format

    def setup(self):
        """配置日志并绑定到 Flask 应用"""
        self._configure_loguru()
        self._redirect_flask_logs()
        return self

    def _configure_loguru(self):
        logger.remove()

        # 控制台日志
        if self.enable_console:
            logger.add(
                sys.stderr,
                format=self.format,
                level=self.log_level,
                enqueue=True,
                colorize=False,
            )

        # 文件日志
        if self.enable_file:
            logger.add(
                self.file_path,
                rotation=self.rotation,
                retention=self.retention,
                compression="zip",
                level=self.log_level,
                format=self.format,
                enqueue=True,
                colorize=False,
            )

    def _redirect_flask_logs(self):
        class InterceptHandler(logging.Handler):
            def emit(self, record):
                logger_opt = logger.opt(depth=6, exception=record.exc_info)
                logger_opt.log(record.levelname, record.getMessage())

        logging.basicConfig(handlers=[InterceptHandler()], level=0)
